package com.ruoyi.system.service.other;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.common.enums.LiveStatus;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.exception.AjaxException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class MqReceiveService {

    @Autowired
    private SysUserAccountMapper sysUserAccountMapper;

    @Autowired
    private SysUserBillcashMapper sysUserBillcashMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserChannelMapper sysUserChannelMapper;

    @Autowired
    private SysOrderMapper sysOrderMapper;


    @Transactional
    public void Ireceive(String message){
        MessageEntity messageEntity = JSONUtil.toBean(message,MessageEntity.class);
        System.out.println("接收到了" + message);
        //支付回调
        if (messageEntity.getKey().equals("pay")){
            SysOrder sysOrder = JSONUtil.toBean(messageEntity.getContent(),SysOrder.class);
            SysUserAccount sysUserAccount = sysUserAccountMapper.selectSysUserAccountById(sysOrder.getUserId());
            if (sysUserAccount==null){
                LogUtils.log.error("用户账号不存在");
                return;
            }
            BigDecimal oldBalance = sysUserAccount.getBalance();
            BigDecimal newBalance = sysUserAccount.getBalance().add(sysOrder.getOrderLastAmount());
            sysUserAccount.setBalance(newBalance);

            SysUserBillcash sysUserBillcash = new SysUserBillcash();
            sysUserBillcash.setRidCode(sysOrder.getOrderCode());
            sysUserBillcash.setChannelId(sysOrder.getChannelId());
            sysUserBillcash.setChannelName(sysOrder.getChannelName());
            sysUserBillcash.setAmount(oldBalance);
            sysUserBillcash.setChangeAmount(sysOrder.getOrderLastAmount());
            sysUserBillcash.setLastAmount(newBalance);
            SysUser sysUser = sysUserMapper.selectUserById(sysOrder.getUserId());
            if (sysUser==null){
                LogUtils.log.error("用户不存在");
                return;
            }
            sysUserBillcash.setUserId(sysUser.getUserId());
            sysUserBillcash.setUserCode(sysUser.getUserCode());
            sysUserBillcash.setLoginName(sysUser.getLoginName());
            sysUserBillcash.setBillcashType(0);
            sysUserBillcash.setBillcashRemark("支付完成");
            sysUserBillcash.setCreateTime(new Date());
            sysUserBillcash.setUpdateTime(new Date());
            try {
                sysUserBillcashMapper.insertSysUserBillcash(sysUserBillcash);
            }catch (Exception e){
                throw new BusinessException("system error:billcash");
            }

            //更新账户失败 放回队列
            if (sysUserAccountMapper.updateSysUserAccount(sysUserAccount)!=1){
                LogUtils.log.warn("更新账户失败");
                throw new BusinessException("system error:account");
            }
            //分润
            if (sysUser.getUserParentId()!=null){
                this.addAgentAccount(sysOrder.getOrderId(),sysOrder.getOrderAmount(),sysUser.getUserParentId(),sysUser.getUserId());
            }

        }else {

        }
    }

    private void addAgentAccount(long orderId,BigDecimal amount,long agentId,long childrenId){
        SysOrder sysOrder = sysOrderMapper.selectSysOrderById(orderId);
        if (sysOrder==null){
            LogUtils.log.error("订单异常");
            return;
        }
        //检查子用户状态
        SysUser children = sysUserMapper.selectUserById(childrenId);
        if (children==null){
            return;
        }
        if (children.getStatus().equals(LiveStatus.DISABLE.getCode())){
            return;
        }
        //检查父用户状态
        SysUser parent = sysUserMapper.selectUserById(agentId);
        if (parent==null){
            return;
        }
        if (parent.getStatus().equals(LiveStatus.DISABLE.getCode())){
            return;
        }
        //检查子用户通道
        SysUserChannel childrenChannel = sysUserChannelMapper.selectSysUserChannelById(childrenId);
        if (childrenChannel==null){
            LogUtils.log.error("用户通道不存在");
            return;
        }
        //检查父用户通道
        SysUserChannel parentChannel = sysUserChannelMapper.selectSysUserChannelById(agentId);
        if (parentChannel==null){
            LogUtils.log.error("代理通道不存在");
            return;
        }
        //父用户赚取的费率
        BigDecimal earnRate1 = childrenChannel.getUserChannelRate1().subtract(parentChannel.getUserChannelRate1());
        if (earnRate1.compareTo(BigDecimal.ZERO)<0){
            LogUtils.log.error("代理费率设置不合理 = {}",parentChannel.getUserChannelRate1());
            return;
        }
        BigDecimal earnFee = childrenChannel.getUserChannelFee().subtract(parentChannel.getUserChannelFee());
        if (earnFee.compareTo(BigDecimal.ZERO)<0){
            LogUtils.log.error("代理费率设置不合理 = {}",parentChannel.getUserChannelFee());
            return;
        }
        //代理分润
       BigDecimal lastEarn =  amount.multiply(earnRate1).add(earnFee);

        SysUserAccount sysUserAccount = sysUserAccountMapper.selectSysUserAccountById(parent.getUserId());
        if (sysUserAccount==null){
            LogUtils.log.error("代理账号不存在");
            return;
        }
        BigDecimal oldBalance = sysUserAccount.getBalance();
        BigDecimal newBalance = sysUserAccount.getBalance().add(lastEarn);
        sysUserAccount.setBalance(newBalance);

        SysUserBillcash sysUserBillcash = new SysUserBillcash();
        //订单信息
        sysUserBillcash.setRidCode(sysOrder.getOrderCode());
        sysUserBillcash.setChannelId(sysOrder.getChannelId());
        sysUserBillcash.setChannelName(sysOrder.getChannelName());
        sysUserBillcash.setAmount(oldBalance);
        sysUserBillcash.setChangeAmount(lastEarn);
        sysUserBillcash.setLastAmount(newBalance);
        //用户信息
        sysUserBillcash.setUserId(parent.getUserId());
        sysUserBillcash.setUserCode(parent.getUserCode());
        sysUserBillcash.setLoginName(parent.getLoginName());
        /** 变动方向（0.支付，1.代付，2.手动增加，3.手动减少，4.佣金，5.其他） */
        sysUserBillcash.setBillcashType(4);
        sysUserBillcash.setBillcashRemark("代理佣金");
        sysUserBillcash.setCreateTime(new Date());
        sysUserBillcash.setUpdateTime(new Date());
        try {
            sysUserBillcashMapper.insertSysUserBillcash(sysUserBillcash);
        }catch (Exception e){
            throw new BusinessException("system error:billcash");
        }

        //更新账户失败 放回队列
        if (sysUserAccountMapper.updateSysUserAccount(sysUserAccount)!=1){
            LogUtils.log.warn("更新账户失败");
            throw new BusinessException("system error:account");
        }

        //递归
        if(parent.getUserParentId()==null){
            return;
        }else {
            addAgentAccount(orderId,amount,parent.getUserParentId(),parent.getUserId());
        }
    }

}
